<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<style>
    #box {
        width: 400px;
        height: 100px;
        margin: auto;
        margin-bottom: 40px;
        border-bottom: 1px solid #ccc;
    }

    * {
        text-align: center;
        font-size: 14px;
    }

    span {
        margin-top: 25px;
    }

    input {
        margin-top: 30px;
    }

    #const {
        margin-top: 30px;
        width: 300px;
        height: 300px;
    }

    #add {
        margin-top: 20px;
    }
</style>

<body>
    <div id="box">

    </div>
    <div id="const">
        标题：<input type="text" id="title"><br>
        <br>
        内容：<textarea name="" id="content" cols="30" rows="10"></textarea>
        <button id="bu1">点击</button>
    </div>
</body>
<script>
    window.onload = function () {
        bu1.onclick = function () {
            var title = document.getElementById("title").value
            var conrnt = document.getElementById("content").value
            var time = Time()
            var obj = {
                title: title,
                content: conrnt,
                time: time
            }
            setlist(obj) //添加
            getlist() //输出
        }
        getlist() //刷新列表
    }

    function setlist(obj) {
        if (!localStorage.getItem("list")) { //判断
            localStorage.setItem("list", JSON.stringify([obj])) //非直接输出
        } else {
            var data = JSON.parse(localStorage.getItem("list")) //获取存储内容转数组
            data.unshift(obj) //头部添加
            localStorage.setItem("list", JSON.stringify(data)) //设置存储为返回添加后的
        }
    }

    function getlist() {
        if (!localStorage.getItem("list")) {
            return
        }
        var data = JSON.parse(localStorage.getItem("list"))
        //    console.log(data);
        var str = ""
        for (let i in data) {
            str += `
       <div id="add">
            <h3>${data[i].title}</h3>
            <p>${data[i].content}</p>
            <span>${data[i].time}<a onclick="dellist(${i})">删除</a></span>
            <hr>
        </div>
       `
        }
        //    console.log(str);
        document.getElementById("box").innerHTML = str
    }

    function dellist(index) {
        var a = JSON.parse(localStorage.getItem("list"))
        a.splice(index, 1)
        localStorage.setItem("list", JSON.stringify(a))
        getlist()
    }

    function Time() {
        var dtime = new Date();
        var nian = dtime.getFullYear(),
            yue = dtime.getMonth() + 1,
            day = dtime.getDate(),
            hours = dtime.getHours(),
            fen = dtime.getMinutes(),
            miao = dtime.getSeconds()
        return nian + "-" + yue + "-" + day + " " + hours + ":" + fen + ":" + miao
    }
</script>

</html>